﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using SportsPlatform.Base;
using SportsPlatform.Dto.SportBusiness.EventsSession;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Query.SportBusiness.EventsSession;
using SportsPlatform.SportBusiness.ISportBusiness;
using SportsPlatform.Consts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using SportsPlatform.SqlExecuter;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 比赛项目场次信息接口服务
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class EventsSessionService : SportsPlatformAppServiceBase, IEventsSessionService
    {

        //比赛项目场次
        private readonly IRepository<EventsSession, Guid> _eventRepository;

        private readonly IRepository<CompetitionProject, Guid> _projectRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        private readonly ISqlExecuterRepository _sqlExecuterRepository;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="eventRepository"></param>
        /// <param name="projectRepository"></param>
        public EventsSessionService(IRepository<EventsSession, Guid> eventRepository, IRepository<UserInfo, Guid> userinfoRepository, IRepository<CompetitionProject, Guid> projectRepository, ISqlExecuterRepository sqlExecuterRepository,
        IHttpContextAccessor context) : base(context)
        {
            _eventRepository = eventRepository;
            _projectRepository = projectRepository;
            _userinfoRepository = userinfoRepository;
            _sqlExecuterRepository = sqlExecuterRepository;
        }

        /// <summary>
        /// 新增比赛项目场次信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddEventsSessionInfo(AddEventsSessionInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                EventsSession events = ObjectMapper.Map<EventsSession>(query);
                events.CreateUserId = token.Id;
                events.CreateTime = DateTime.Now;
                //if (query.ParentID == null || query.ParentID == Guid.Empty)
                //{
                //    events.ParentID = Guid.Empty;
                //}
                //else
                //{
                //    //判断父级是否存在及父级的比赛项目id是否相同
                //    if (_eventRepository.FirstOrDefault(info => info.Id == events.ParentID && info.CompetitionProjectId==events.CompetitionProjectId) == null)
                //    {
                //        baseResultDto.Code = HttpResultCode.Fail;
                //        baseResultDto.IsSuccess = false;
                //        baseResultDto.Message = "传入父级Id不存在！";
                //        return baseResultDto;
                //    }
                //}
                if (_projectRepository.FirstOrDefault(info => info.Id == events.CompetitionProjectId) == null)
                {
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Message = "传入比赛项目Id不存在！";
                }
                else
                {
                    await _eventRepository.InsertAsync(events);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "新增成功！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.IsSuccess = false;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
        /// <summary>
        /// 场次信息同步
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> EventsSessionInfoSynchronization(List<EventsSessionInfoSynchronizationQuery> query)
        {
            BaseResultDto resultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                //同步之前删除之前项目Id的分组
                var competitionProjectIdlist = query
                    .GroupBy(group => new { group.CompetitionProjectId })
                    .Select(group => group.FirstOrDefault())
                    .ToList();
                competitionProjectIdlist.ForEach(item =>
                {
                    var sql = "UPDATE T_B_EventsSession SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where CompetitionProjectId='" + item.CompetitionProjectId + "'";
                    _sqlExecuterRepository.Execute(sql, null);
                });

                var projectlist = await _projectRepository.GetAllListAsync();
                var userlist = await _userinfoRepository.GetAllListAsync();
                var eventlist = await _eventRepository.GetAllListAsync();
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Fail;
                foreach (var item in query)
                {
                    var eventinfo = ObjectMapper.Map<EventsSession>(item);
                    #region 验证数据
                    if (item.Id == null && item.Id == Guid.Empty)
                    {
                        eventinfo.Id = Guid.NewGuid();
                    }
                    if (projectlist.FirstOrDefault(info => info.Id == item.CompetitionProjectId) == null)
                    {
                        resultDto.Message += $"项目Id:{item.CompetitionProjectId}不存在;";
                        continue;
                    }
                    if (item.Race != 1 && item.Race != 2)
                    {
                        resultDto.Message += $"赛程{item.CompetitionProjectId}不存在，1：预赛，2决赛;";
                        continue;
                    }
                    if (item.CreateTime == null)
                    {
                        eventinfo.CreateTime = DateTime.Now;
                    }
                    if (item.CreateUserId == null || item.CreateUserId == Guid.Empty)
                    {
                        eventinfo.CreateUserId = token.Id;
                    }
                    else
                    {
                        if (userlist.FirstOrDefault(info => info.Id == item.CreateUserId) == null)
                        {
                            resultDto.Message += $"创建人{item.CreateUserId}不存在;";
                            continue;
                        }
                    }
                    #endregion
                    var info = eventlist.FirstOrDefault(info => info.Id == eventinfo.Id);
                    if (info == null)
                    {
                        await _eventRepository.InsertAsync(eventinfo);
                    }
                    else
                    {
                        info.CompetitionProjectId = eventinfo.CompetitionProjectId;
                        info.MatchType = eventinfo.MatchType;
                        info.Race=eventinfo.Race;
                        info.CreateTime = eventinfo.CreateTime;
                        info.CreateUserId = eventinfo.CreateUserId;
                        info.IsDeleted = eventinfo.IsDeleted;
                        info.UpdateTime = eventinfo.UpdateTime;
                        info.UpdateUserId = eventinfo.UpdateUserId;
                        info.DeleteTime = eventinfo.DeleteTime;
                        info.DeleteUserId = eventinfo.DeleteUserId;
                        await _eventRepository.UpdateAsync(info);
                    }

                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                }
                resultDto.Message = string.IsNullOrEmpty(resultDto.Message) ? "操作成功！" : resultDto.Message;
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 删除比赛项目场次信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> DeleteEventsSessionInfo(DeleteOrGetModelQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var ret = await _eventRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (ret != null)
                {
                    ret.DeleteUserId = token.Id;
                    ret.DeleteTime = DateTime.Now;
                    ret.IsDeleted = true;
                    await _eventRepository.UpdateAsync(ret);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "删除成功！";
                }
                else
                {
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Message = "未查询到需要删除的数据！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.IsSuccess = false;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 获取比赛项目场次树型数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<EventsSessionTreeInfoDto>> GetEventsSessionTreeInfo(GetEventsSessionTreeInfoQuery query)
        {
            ResultListDto<EventsSessionTreeInfoDto> resultListDto = new ResultListDto<EventsSessionTreeInfoDto>();
            try
            {
                var result = await GetEventsSessionTreeList(Guid.Empty, query.CompetitionProjectId);
                if (result != null && result.Count() > 0)
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = result;
                }
                else
                {
                    resultListDto.Code = HttpResultCode.Fail;
                    resultListDto.IsSuccess = false;
                    resultListDto.Message = "未获取到比赛项目场次！";
                }
            }
            catch (Exception e)
            {
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.IsSuccess = false;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 递归获取树型菜单
        /// </summary>
        /// <param name="ParentId"></param>
        /// <param name="CompetitionProjectId"></param>
        /// <returns></returns>
        public async Task<List<EventsSessionTreeInfoDto>> GetEventsSessionTreeList(Guid ParentId, Guid CompetitionProjectId)
        {
            List<EventsSessionTreeInfoDto> resultListDto = new List<EventsSessionTreeInfoDto>();
            try
            {
                //var ret = await _eventRepository.GetAllListAsync(info => info.ParentID == ParentId && info.CompetitionProjectId == CompetitionProjectId && info.IsDeleted == false);
                //if (ret != null && ret.Count > 0)
                //{
                //    foreach (EventsSession item in ret)
                //    {
                //        var treelist = await GetEventsSessionTreeList(item.Id, CompetitionProjectId);
                //        EventsSessionTreeInfoDto dto = new EventsSessionTreeInfoDto();
                //        dto.Id= item.Id;
                //        dto.MatchType= item.MatchType;
                //        dto.Children= (treelist != null && treelist.Count() > 0) ? treelist : null;
                //        resultListDto.Add(dto);
                //    }
                //}
            }
            catch
            {

            }
            return resultListDto;
        }

        /// <summary>
        /// 更新比赛项目场次信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdteEventsSessionInfo(UpdteEventsSessionInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var ret = await _eventRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (ret != null)
                {
                    ret.MatchType = query.MatchType;
                    ret.Race = query.Race;
                    await _eventRepository.UpdateAsync(ret);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Message = "未查询到需要更改的数据！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.IsSuccess = false;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 获取比赛项目场次数据列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetEventsSessionListDto>> GetEventsSessionList([FromBody] GetEventsSessionListQuery query)
        {
            var res = new ResultListDto<GetEventsSessionListDto>();
            var es = await _eventRepository.GetAllListAsync(a => a.CompetitionProjectId == query.ProjectId && a.IsDeleted == false);
            var project = await _projectRepository.GetAsync(query.ProjectId);
            if (es.Count > 0)
            {
                var list = new List<GetEventsSessionListDto>();
                var dto = new GetEventsSessionListDto();
                foreach (var item in es)
                {
                    dto = new GetEventsSessionListDto();
                    dto.Id = item.Id;
                    dto.Race = item.Race == 1 ? "预赛" : "决赛";
                    dto.MatchType = item.MatchType;
                    dto.CompetitionProject = project.Name;
                    list.Add(dto);
                }
                res.Code = HttpResultCode.Success;
                res.Count = list.Count;
                res.Data = list;
                res.IsSuccess = true;
                res.Message = "查询成功";
            }
            else
            {
                res.Code = HttpResultCode.NotData;
                res.Count = 0;
                res.Message = "未查询到数据";
                res.IsSuccess = true;
            }

            return res;
        }
    }
}
